<template>
  <div class="page-container">
    <div class="form-container">
      <el-form
        :inline="true"
        label-suffix="："
        :label-width="'100px'"
        :size="'small'"
        ref="form"
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="业务编号">
              <el-input
                v-model="state.query.doccode"
                clearable
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结算对象名称" label-width="100px">
              <el-select
                v-model="state.query.entId"
                placeholder="请选择结算对象"
                style="width: 100%"
                clearable
                filterable
                remote
                :remote-method="getBusDetail"
                :loading="state.settlementLoading"
              >
                <el-option
                  v-for="item in state.settlementList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right">{{ item.entFullname }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="提单号">
              <el-input
                v-model="state.query.blNo"
                clearable
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员">
              <el-select
                v-model="state.query.salesId"
                placeholder="请选择业务员"
                style="width: 100%"
                clearable
                filterable
                remote
                :remote-method="getSalesman"
                :loading="state.salesmanLoading"
              >
                <el-option
                  v-for="item in state.salesman"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="币种">
              <el-select
                v-model="state.query.currency"
                placeholder="请选择币种"
                style="width: 100%"
                clearable
                filterable
                remote
                :remote-method="getCurrentData"
                :loading="state.currentLoading"
              >
                <el-option
                  v-for="item in state.current"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left"> {{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核状态">
              <el-select
                v-model="state.query.checkStatus"
                placeholder="请选择审核状态"
                style="width: 100%"
                filterable
                :disabled="true"
              >
                <el-option
                  v-for="item in state.aduitStatus"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="核销状态">
              <el-select
                v-model="state.query.feeStatus"
                placeholder=" "
                style="width: 100%"
                filterable
              >
                <el-option label="全部" :value="-2"> </el-option>
                <el-option label="已核销" :value="1"> </el-option>
                <el-option label="未核销" :value="0"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="收/付">
              <el-select
                v-model="state.query.isIncome"
                placeholder=" "
                style="width: 100%"
                filterable
              >
                <el-option label="全部" :value="-2"> </el-option>
                <el-option label="应收" :value="1"> </el-option>
                <el-option label="应付" :value="0"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="flex-container">
          <!-- <el-button
            type="primary"
            @click="state.hidden = !state.hidden"
            size="small"
            style="padding: 8px 15px"
          >
            <div class="flex-container">
              <el-icon style="transform: rotate(90deg)">
                <MoreFilled />
              </el-icon>
              {{ hidden ? "折叠" : "更多条件" }}
            </div>
          </el-button> -->
          <el-button type="primary" icon="search" @click="getList" size="small">
            搜索
          </el-button>
          <el-button type="info" icon="refresh" @click="reset" size="small">
            重置
          </el-button>
        </div>
      </el-form>
    </div>
    <div style="margin-top: 8px" class="contentcontainer">
      <div class="btn-box">
        <el-button type="default" icon="RefreshRight" @click="getList">
        </el-button>
        <el-button type="primary" icon="EditPen" @click="modifyInvioce">
          开票
        </el-button>
      </div>
      <!-- :autostyle="'height:calc(100% - 80px)'" @update:option="upDataOption"-->
      <AppPageTable
        stripe
        :data="state.tableData.data"
        @change="getList"
        :height="500"
        :option="state.tableData.option"
        v-loading="state.tableLoading"
      >
        <el-table-column
          type="selection"
          width="40"
          align="center"
          fixed="left"
        />
        <el-table-column
          prop="doccode"
          width="200"
          align="center"
          label="业务编号"
          showOverflowTooltip
        >
          <template #default="scope">
            <span class="doccode-text" @click="toEditPage(scope.row)">{{
              scope.row.doccode
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="blNo"
          width="200"
          align="center"
          label="提单号"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="recDate"
          width="100"
          align="center"
          label="接单日期"
          showOverflowTooltip
        >
          <template #default="scope">
            {{
              scope.row.recDate
                ? $utils.formatDateTime(scope.row.recDate, 'YYYY-MM-DD')
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="etd"
          width="100"
          align="center"
          label="开航日期"
          showOverflowTooltip
        >
          <template #default="scope">
            {{
              scope.row.etd
                ? $utils.formatDateTime(scope.row.etd, 'YYYY-MM-DD')
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="packTime"
          width="100"
          align="center"
          label="装箱日期"
          showOverflowTooltip
        >
          <template #default="scope">
            {{
              scope.row.packTime
                ? $utils.formatDateTime(scope.row.packTime, 'YYYY-MM-DD')
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="vessel"
          align="center"
          label="船名"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="voyage"
          align="center"
          label="航次"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="portDepartureName"
          align="center"
          label="起运港"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="portDestinationName"
          align="center"
          label="目的港"
          showOverflowTooltip
        >
        </el-table-column>
        <!-- <el-table-column
                  prop="shipCompanyName"
                  label="船公司"
                  align="center"
                  width="200"
                  showOverflowTooltip
              >
              </el-table-column> -->
        <el-table-column
          prop="entFullname"
          label="结算对象名称"
          align="center"
          width="200"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          label="收/付"
          align="center"
          width="100"
          showOverflowTooltip
        >
          <template #default="scope">
            {{ scope.row.isIncome == 1 ? '收款' : '付款' }}
          </template>
        </el-table-column>
        <el-table-column label="费用名称" align="center" width="100">
          <template #default="scope">
            {{ scope.row.feeName }}
          </template>
        </el-table-column>
        <el-table-column
          prop="currency"
          label="币种"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="totalmoney"
          label="金额"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="verificationMoney"
          label="已销金额"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="getUnVerificationMoney"
          label="未销金额"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="natMoney"
          width="100"
          align="center"
          label="折人民币"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          label="审核"
          align="center"
          width="100"
          showOverflowTooltip
        >
          <template #default="scope">
            {{ scope.row.checkStatus == 1 ? '已审' : '未审' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="checkName"
          width="100"
          align="center"
          label="审核人"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          prop="checkTime"
          width="100"
          align="center"
          label="审核日期"
          showOverflowTooltip
        >
          <template #default="scope">
            {{
              scope.row.checkTime
                ? $utils.formatDateTime(
                    scope.row.checkTime,
                    'YYYY-MM-DD HH:mm:ss'
                  )
                : ''
            }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="invoiceCode"
          label="发票号"
          align="center"
          width="100"
          showOverflowTooltip
        >
        </el-table-column>
        <el-table-column
          label="开票日期"
          align="center"
          width="100"
          showOverflowTooltip
        >
          <template #default="scope">
            {{
              scope.row.invoiceDate
                ? $utils.formatDateTime(scope.row.invoiceDate, 'YYYY-MM-DD')
                : ''
            }}
          </template>
        </el-table-column> -->
        <el-table-column
          prop="memo"
          align="center"
          label="备注"
          showOverflowTooltip
        >
        </el-table-column>
      </AppPageTable>
    </div>
    <InvoiceDialog
      ref="invoiceDialog"
      :hasAccount="false"
      @getList="getList"
    ></InvoiceDialog>
  </div>
</template>

<script setup>
import { defineComponent, ref, reactive, onMounted } from 'vue'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import request from '@/public/request'
import dayjs from 'dayjs'
import { MoreFilled } from '@element-plus/icons'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import InvoiceDialog from './components/InvoiceDialog.vue'

const Route = useRoute()
const Router = useRouter()

const invoiceDialog = ref()

const state = reactive({
  // 查询条件
  query: {
    doccode: '', //业务编号
    entId: '', //结算对象名称
    blNo: '', //提单号
    salesId: '', //业务员
    checkStatus: 1, //审核状态
    currency: '', //币种
    // invoiceStatus: -2, //开票状态 0 未开票 1 已开票
    isIncome: -2, // 1:应收 0:应付
    feeStatus: -2 //核销状态 0 未核销 1 已核销
  },
  //表格数据
  tableData: {
    data: [],
    option: useTableOption()
  },
  tableLoading: false,
  // 展开
  hidden: false,
  // 结算对象的数据
  settlementList: [],
  settlementLoading: false,
  // 币种
  current: [],
  currentLoading: false,
  // 业务员
  salesman: [],
  salesmanLoading: false,
  // 核销状态
  WriteOffStatus: [
    {
      label: '全部',
      value: -2
    },
    {
      label: '未核销',
      value: 0
    },
    {
      label: '已核销',
      value: 1
    }
  ],
  // 审核状态
  aduitStatus: [
    {
      label: '全部',
      value: -2
    },
    {
      label: '未审核',
      value: 0
    },
    {
      label: '已审核',
      value: 1
    }
  ],
  //费用类型
  feenameList: [],
  feenameLoading: false,
  // 币种数组
  curList: [],
  // 统计计算
  resultStatistical: {
    // 合计
    amount: {
      _in: [],
      _out: [],
      _profit: []
    },
    // 已核对
    checked: {
      _in: [],
      _out: [],
      _profit: []
    },
    //选中
    selected: {
      _in: [],
      _out: [],
      _profit: []
    }
  }
})

// 获取币种类型
const getCurrentData = async (val) => {
  state.currentLoading = true
  let res = await request.get('/api/base/currency/dropdownlist', {
    keywords: val
  })
  state.current = res.map((item) => {
    return {
      label: item.currencyCode + '|' + item.currencyName,
      value: item.currencyCode
    }
  })
  state.currentLoading = false
}

// 跳转业务详情页面
const toEditPage = (row) => {
  Router.openTab({
    path: '/business/docDetail',
    query: {
      id: row.docId,
      title: `业务详情${row.doccode}`,
      iscopy: false
    }
  })
}

// 获取列表数据
const getList = async () => {
  let search = {
    PageIndex: state.tableData.option.page,
    PageSize: state.tableData.option.pageSize,
    ...JSON.parse(JSON.stringify(state.query))
  }
  let queryKeysList = Object.keys(state.query)
  for (const iterator of queryKeysList) {
    // if (state.query[iterator] instanceof Array) {
    //   if (state.query[iterator].length === 0) {
    //     delete search[iterator]
    //   }
    // } else {
    if (state.query[iterator] === -2) {
      search[iterator] = ''
    }
    // }
  }
  state.tableLoading = true
  let res = await request.get('/api/invoice/noInvoiceList', search)

  state.tableData.data = res.content
  state.tableData.option.total = res.totalElements
  state.tableLoading = false
}

// 应付页面合计数据加一个负号
const addMinus = (resList) => {
  if (state.DocType == 0) {
    resList._profit.forEach((item) => {
      item.money = item.money * -1
    })
  }
}

// 统计个币种的计算结果
const statisticCurResult = (list) => {
  for (const iterator of list) {
    if (state.curList.indexOf(iterator.currency) === -1) {
      state.curList.push(iterator.currency)
    }
  }
}

// 复选框变动
const upDataOption = (inOption) => {
  let selected = state.tableData.option.selected
  state.resultStatistical.selected = {
    _in: [],
    _out: [],
    _profit: []
  }
  for (const iterator of state.curList) {
    let curObj = {
      currency: iterator,
      money: 0
    }
    state.resultStatistical.selected._in.push(
      JSON.parse(JSON.stringify(curObj))
    )
    state.resultStatistical.selected._out.push(
      JSON.parse(JSON.stringify(curObj))
    )
    state.resultStatistical.selected._profit.push(
      JSON.parse(JSON.stringify(curObj))
    )
  }
  for (const item of selected) {
    if (state.curList.indexOf(item.currency) != -1) {
      if (item.isIncome == 1) {
        addCurCount(
          item.getTotalmoney,
          item.currency,
          state.resultStatistical.selected._in
        )
      } else if (item.isIncome == 0) {
        addCurCount(
          item.getTotalmoney,
          item.currency,
          state.resultStatistical.selected._out
        )
      }
    }
  }

  // 计算各币种对应的合计
  for (const iterator of state.resultStatistical.selected._profit) {
    let index = state.curList.indexOf(iterator.currency)
    let _in = state.resultStatistical.selected._in
    let _out = state.resultStatistical.selected._out
    let _profit = state.resultStatistical.selected._profit
    if (state.DocType == 1) {
      _profit[index].money = _in[index].money - _out[index].money
    } else {
      _profit[index].money = _out[index].money - _in[index].money
    }
  }
}

const addCurCount = (curMoney, cur, list) => {
  for (const iterator of list) {
    if (iterator.currency == cur) {
      iterator.money += curMoney
    }
  }
}

// 重置
const reset = () => {
  state.query = {
    doccode: '', //业务编号
    entId: '', //结算对象名称
    blNo: '', //提单号
    salesId: '', //业务员
    checkStatus: 1, //审核状态
    currency: '', //币种
    // invoiceStatus: -2, //开票状态 0 未开票 1 已开票
    isIncome: -2, // 1:应收 0:应付
    feeStatus: -2 //核销状态 0 未核销 1 已核销
  }
  getList()
}

// 批量审核和取消
const batchAduit = async (val) => {
  if (!state.tableData.option.selected.length) {
    ElMessage.warning('请选择数据')
    return
  }
  let req = {
    ids: [],
    checkStatus: val
  }
  for (const iterator of state.tableData.option.selected) {
    req.ids.push(iterator.id)
  }
  let res = await request.post('/api/docbalance/createBalance', req)
  if (res.status) {
    getList()
    ElMessage.success('成功')
  } else {
    ElMessage.warning(res.message)
  }
}

// 新增开单
const modifyInvioce = async () => {
  if (state.tableData.option.selected.length < 1) {
    ElMessage.warning('请至少选择一条数据！')
    return
  }
  let selectedValue = state.tableData.option.selected
  invoiceDialog.value.openDialog(selectedValue)
}

// 获取结算对象的数据
const getBusDetail = async (val) => {
  state.settlementLoading = true
  let res = await request.get('/api/buenterprise/dropdownlist', {
    KeyWords: val
  })
  res.forEach((item) => {
    item.label = item.entCode
    item.value = item.id
  })
  state.settlementList = res
  state.settlementLoading = false
}

// 获取业务员
const getSalesman = async (val) => {
  state.salesmanLoading = true
  let res = await request.get('/api/user/userList', {
    keyword: val
  })
  res.forEach((item) => {
    item.label = item.nickName
    item.value = item.id
  })
  state.salesman = res
  state.salesmanLoading = false
}

// 获取费用类型
const getFeeType = async (val) => {
  state.feenameLoading = true
  let res = await request.get('/api/base/feetype/query', {
    KeyWords: val
  })
  res.content.forEach((item) => {
    item.label = item.feeName
    item.value = item.feeName
  })
  state.feenameList = res.content
  state.feenameLoading = false
}

onMounted(() => {
  getCurrentData()
  getList()
})
</script>

<style lang="scss" scoped>
.form-container {
  border: 1px solid #e8e8e8;
  padding: 6px 6px 6px 8px;
  background-color: #ffffff;

  :deep(.el-form-item--small .el-form-item__label) {
    font-size: 12px;
    color: rgba(0, 0, 0, 0.85);
  }

  :deep(.el-input--suffix .el-input__inner) {
    padding-right: 4px;
  }

  :deep(.el-form--inline .el-form-item) {
    display: flex;
    margin-right: 0;
  }

  :deep(.el-form-item--small.el-form-item) {
    margin-bottom: 8px;
  }
}

.btn-box {
  margin-bottom: 8px;
}

.flex-container {
  display: flex;
}

.doccode-text {
  color: rgb(24, 144, 255);
  cursor: pointer;
}

// .button-container {
//     display: flex;
//     justify-content: flex-end;
//     align-items: center;
// }

.statistical-results {
  padding-left: 20px;
  padding-right: 20px;

  .statistical-tip {
    display: inline-block;
    background: #2867c9;
    width: 4px;
    height: 20px;
    vertical-align: middle;
    margin-left: -20px;
  }

  .statistical-label {
    margin: 0 16px;
    display: inline-block;
    font-weight: 600;
    color: #000000a6;
  }

  .statistical-text {
    color: red;
    font-size: 12px;
    line-height: 18px;
  }
}

.doccode-text {
  color: rgb(24, 144, 255);
  cursor: pointer;
}

.contentcontainer {
  width: 100%;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  background-color: white;
  padding: 8px;
}
</style>
